package com.example.qiandao.controller;

import com.example.qiandao.common.Result;
import com.example.qiandao.entity.User;
import com.example.qiandao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService; // 注入 UserService


    @PostMapping("/wx/login")
    public Result wxLogin(@RequestBody Map<String, Object> params) {
        // 校验 payload 是否包含 "code" 字段
        Object codeObj = params.get("code");
        String code;
        if (codeObj instanceof String) {
            code = (String) codeObj;
        } else if (codeObj instanceof Map) {
            // 如果 code 是嵌套的 Map，尝试提取实际值
            Map<?, ?> codeMap = (Map<?, ?>) codeObj;
            code = String.valueOf(codeMap.get("code"));
        } else {
            return Result.error(400, "Invalid 'code' format in request payload");
        }

        try {
            // 调用 UserService 处理微信登录逻辑
            Map<String, Object> result = userService.wxLogin(code);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    @PostMapping("/register")
    public Result register(@RequestBody Map<String, Object> params) {
        Long userId = ((Integer) params.get("userId")).longValue();
        String name = String.valueOf(params.get("name"));
        Integer role = (Integer) params.get("role");

        try {
            // 调用 UserService 处理用户注册逻辑
            String message = userService.register(userId, name, role);
            return Result.success(message);
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 根据班级 ID 查询该班级下的所有学生
     */
    @GetMapping("/students/{classId}")
    public Result getStudentsByClassId(@PathVariable Long classId) {

        List<User> students = userService.getStudentsByClassId(classId);
        if (students == null || students.isEmpty()) {
            return Result.success("No students found in this class");
        }

        // 返回学生列表
        return Result.success(students);
    }
}